(library (string-utils)
  (export char->string
          string->char
          has-prefix?
          has-suffix?
          remove-prefix
          remove-suffix
          remove-multiple-prefix
          remove-multiple-suffix)
  (import
    (except (rnrs base) let-values)
    (only (guile)
          ;; lambda forms
          lambda* λ
          ;; file system stuff
          ;; string stuff
          string-null?
          string-trim-right
          string-split
          string-contains
          string-suffix-length
          string-prefix-length)
    (ice-9 exceptions)
    (prefix (logging) log:)))


(define char->string
  (λ (c)
    (list->string
     (list c))))


(define string->char
  (λ (str)
    "Convert a string, which has only one single character
into a character. This is useful, because some functions
expect a characters as input instead of a string."
    (cond
     [(= (string-length str) 1)
      (car (string->list str))]
     [else
      (raise-exception
       (make-exception
        (make-non-continuable-error)
        (make-exception-with-message "trying to convert string of more than 1 character to char")
        (make-exception-with-irritants (list str))
        (make-exception-with-origin 'string->char)))])))


(define has-prefix?
  (λ (str prefix)
    (= (string-prefix-length str prefix)
       (string-length prefix))))


(define has-suffix?
  (λ (str suffix)
    (= (string-suffix-length str suffix)
       (string-length suffix))))


(define remove-prefix
  (λ (str prefix)
    (cond
     [(has-prefix? str prefix)
      (substring str (string-length prefix))]
     [else str])))


(define remove-suffix
  (λ (str suffix)
    (cond
     [(has-suffix? str suffix)
      (substring str
                 0
                 (- (string-length str)
                    (string-length suffix)))]
     [else str])))


(define remove-multiple-prefix
  (λ (str prefix)
    (cond
     [(has-prefix? str prefix)
      (remove-multiple-prefix (substring str (string-length prefix))
                              prefix)]
     [else str])))


(define remove-multiple-suffix
  (λ (str suffix)
    (cond
     [(has-suffix? str suffix)
      (remove-multiple-suffix (substring str 0 (- (string-length str)
                                                  (string-length suffix)))
                              suffix)]
     [else str])))
